<?php

/**
 * 登录控制器
 */
class LoginController extends \Our\Controller_AbstractAdmin
{
    /**
     * 登录页面
     */
    public function indexAction()
    {
        $business = \Admin\AdminModel::getInstance();
        $admin = $business->validateLogin();
        if ($admin) {
            $this->redirect("/admin/admin/index/");
            exit();
        }
        $form = new \Admin\AdminLoginFormModel($this->_getPost());
        if ($this->getRequest()->isPost()) {
            $form->setData($this->_getPost());
        }
        if ($this->getRequest()->isPost() && $form->validate()) {
            $params = $form->getFieldValue();
            try {
                $business = \Admin\AdminModel::getInstance();
                $admin = $business->login($params['admin_email'], $params['admin_password']);
                $this->redirect('/admin/admin/index/');
                exit();
            } catch (Exception $e) {
                if (!($e->getCode() > 10000)) {
                    throw $e;
                }
                $this->_assignErrorMessage($e->getMessage(), $e->getCode());
            }
        }
        $this->_assign("form", $form);
    }

    /**
     * 用户登出
     */
    public function logoutAction()
    {
        \Yaf\Dispatcher::getInstance()->disableView();
        $AdminModel = \Admin\AdminModel::getInstance();
        $AdminModel->logout();
        $this->redirect('/admin/login/index/');
        exit();
    }

    /**
     * 生成验证图片
     */
    public function checkauthAction()
    {
        \Yaf\Dispatcher::getInstance()->disableView();
        header("Content-type:image/png");
        $imgWidth = 120;
        $imgHeight = 34;
        $chars = 'ABCDEFGHIJKLMNPQRST23456789';
        mt_srand((double)microtime() * 1000000 * getmypid());
        $newNumber = '';
        while (strlen($newNumber) < 6)
            $newNumber .= substr($chars, (mt_rand() % strlen($chars)), 1);

        $checkAuth = $newNumber;
        $container = new \Zend\Session\Container('auth');
        $container->auth = $newNumber;

        $newNumber = imageCreate($imgWidth, $imgHeight); //创建图象
        ImageColorAllocate($newNumber, 255, 255, 255);  //设置背景色为白色

        for ($i = 0; $i < 6; $i++) {
            $font = mt_rand(5, 8);
            $x = mt_rand(1, 8) + $imgWidth * $i / 6;
            $y = mt_rand(1, $imgHeight / 3);
            $color = imageColorAllocate($newNumber, mt_rand(0, 100), mt_rand(0, 150), mt_rand(0, 200)); //设置字符颜色
            imageString($newNumber, $font, $x, $y, $checkAuth[$i], $color); //输出字符
        }

        ImagePng($newNumber);
        ImageDestroy($newNumber);
    }

}
